package com.lisa.auto.service.c3.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.lisa.auto.entity.c3.model.CarModel;
import com.lisa.auto.entity.c3.model.CarSeries;
import com.lisa.auto.entity.c3.response.BaseResponse;
import com.lisa.auto.enums.C3UrlEnum;
import com.lisa.auto.mapper.c3.CarSeriesMapper;
import com.lisa.auto.service.c3.C3CarModelService;
import com.lisa.auto.service.c3.CarSeriesService;
import com.lisa.auto.util.basic.BaseException;
import demo.C3ApiDemo;
import demo.request.SeriesListRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 车系管理 服务实现类
 * </p>
 *
 * @author hxh
 * @since 2019-12-20
 */
@Service
public class CarSeriesServiceImpl extends ServiceImpl<CarSeriesMapper, CarSeries> implements CarSeriesService {

    @Value("${c3.url}")
    private String c3url;
    @Value("${c3.appKey}")
    private String appKey;
    @Value("${c3.secretKey}")
    private String secretKey;

    @Autowired
    private C3CarModelService modelService;

    @Override
    public List<CarSeries> queryCarSeriesToSave(String brandNo) {
        try {
            String url = c3url + C3UrlEnum.SERIESURL.getUrl();
            SeriesListRequest request = new SeriesListRequest();
            request.setAppKey(appKey);
            request.setBrandNo(brandNo);
            String requestJson = JSONObject.toJSONString(request);
            String result = C3ApiDemo.get(url, requestJson, secretKey);
            if (StringUtils.isNotBlank(result)) {
                BaseResponse<CarSeries> baseResponse = JSONObject.parseObject(result, BaseResponse.class);
                JSONObject jsonObject = JSONObject.parseObject(result);
                if (!baseResponse.isReturnSuccess()) {
                    throw new BaseException("获取品牌信息查询:" + baseResponse.getReturnErrMsg());
                }
                List<CarSeries> list = JSON.parseArray(JSON.toJSONString(jsonObject.get("list")), CarSeries.class);
                if (list != null) {
                    EntityWrapper<CarSeries> wrapper = new EntityWrapper<>();
                    wrapper.eq("brand_no", brandNo);
                    baseMapper.delete(wrapper);
                    for (CarSeries carSeries : list) {
                        if (StringUtils.isNotBlank(carSeries.getNo()))
                            baseMapper.insert(carSeries);
                    }
                }
                return list;
            }
            return null;
        } catch (IOException e) {
            throw new BaseException(e.getMessage());
        } catch (Exception e) {
            throw new BaseException(e.getMessage());
        }
    }

    @Override
    public void addCarSeries(CarSeries carSeries) {
        if (StringUtils.isEmpty(carSeries.getNo())) {
            throw new BaseException("车系编码不能为空");
        }
        if (StringUtils.isEmpty(carSeries.getName())) {
            throw new BaseException("车系名称不能为空");
        }
        if (StringUtils.isEmpty(carSeries.getBrandNo())) {
            throw new BaseException("品牌编码不能为空");
        }
        if (StringUtils.isEmpty(carSeries.getBrandName())) {
            throw new BaseException("品牌名称不能为空");
        }
        //查询该车架号是否已存在，存在就更新，不存在就新增
        EntityWrapper<CarSeries> ew = new EntityWrapper<>();
        ew.eq("no", carSeries.getNo());
        List<CarSeries> carSeriesList = baseMapper.selectList(ew);
        if (carSeriesList != null && !carSeriesList.isEmpty()) {
            baseMapper.update(carSeries, ew);
        } else {
            baseMapper.insert(carSeries);
        }
    }

    @Override
    public List<CarSeries> getCarSeriesList(Map<String, Object> condition) {
        EntityWrapper<CarSeries> ew = buildWrapper(condition);
        List<CarSeries> list = baseMapper.selectList(ew);
        return list;
    }

    @Override
    public Page<CarSeries> getCarSeriesListPage(Page<CarSeries> page) {
        if (page == null) {
            throw new BaseException("参数不能为空");
        }
        EntityWrapper<CarSeries> ew = buildWrapper(page.getCondition());
        List<CarSeries> list = baseMapper.getCarSeriesListPage(ew, page);
        page.setRecords(list);
        return page;
    }

    private EntityWrapper<CarSeries> buildWrapper(Map<String, Object> cd) {
        EntityWrapper<CarSeries> ew = new EntityWrapper<>();
        if (cd != null) {
            if (Objects.nonNull(cd.get("no")) &&
                    StringUtils.isNotBlank(cd.get("no").toString())) {
                ew.like("no", cd.get("no").toString());
            }
            if (Objects.nonNull(cd.get("name")) &&
                    StringUtils.isNotBlank(cd.get("name").toString())) {
                ew.like("name", cd.get("name").toString());
            }
            if (Objects.nonNull(cd.get("brandNo")) &&
                    StringUtils.isNotBlank(cd.get("brandNo").toString())) {
                ew.like("brand_no", cd.get("brandNo").toString());
            }
            if (Objects.nonNull(cd.get("brandName")) &&
                    StringUtils.isNotBlank(cd.get("brandName").toString())) {
                ew.like("brand_name", cd.get("brandName").toString());
            }
            if (Objects.nonNull(cd.get("status")) &&
                    StringUtils.isNotBlank(cd.get("status").toString())) {
                ew.eq("status", cd.get("status").toString());
            }
            if (Objects.nonNull(cd.get("startDate")) && StringUtils.isNotEmpty((String) cd.get("startDate"))) {
                ew.ge("gmt_create", cd.get("startDate").toString());
            }
            if (Objects.nonNull(cd.get("endDate")) && StringUtils.isNotEmpty((String) cd.get("endDate"))) {
                ew.le("gmt_create", cd.get("endDate").toString());
            }
        }
        ew.orderBy("gmt_create", Boolean.FALSE);
        return ew;
    }

    @Override
    public void deleteById(Long id) {
        baseMapper.deleteById(id);
    }

    @Override
    public void forbiddenByIds(String id) {
        if (StringUtils.isEmpty(id)) throw new BaseException("参数为空");
        String[] ids = id.split(",");
        EntityWrapper<CarSeries> ew = new EntityWrapper<>();
        ew.in("id", ids);
        List<CarSeries> carSeriesList = baseMapper.selectList(ew);
        if (carSeriesList == null || carSeriesList.size() < 1) throw new BaseException("未查询到对应车系信息");
        for (CarSeries carSeries : carSeriesList) {
            if ("50".equals(carSeries.getStatus())) throw new BaseException("存在已删除车系");
            if ("40".equals(carSeries.getStatus())) throw new BaseException("存在已禁用车系");
        }
        CarSeries info = new CarSeries();
        info.setStatus("40");
        info.setGmtModified(new Date());
        baseMapper.update(info, ew);
    }

    @Override
    public void enableByIds(String id) {
        if (StringUtils.isEmpty(id)) throw new BaseException("参数为空");
        String[] ids = id.split(",");
        EntityWrapper<CarSeries> ew = new EntityWrapper<>();
        ew.in("id", ids);
        List<CarSeries> carSeriesList = baseMapper.selectList(ew);
        if (carSeriesList == null || carSeriesList.size() < 1) throw new BaseException("未查询到对应车系信息");
        for (CarSeries carSeries : carSeriesList) {
            if ("50".equals(carSeries.getStatus())) throw new BaseException("存在已删除车系");
            if ("10".equals(carSeries.getStatus())) throw new BaseException("存在已启用车系");
        }
        CarSeries info = new CarSeries();
        info.setStatus("10");
        info.setGmtModified(new Date());
        baseMapper.update(info, ew);
    }

    @Override
    public Page<CarSeries> getSeriesAndModelList(Page<CarSeries> page) {
        if (page == null) {
            throw new BaseException("参数不能为空");
        }
        EntityWrapper<CarSeries> ew = buildWrapper(page.getCondition());
        List<CarSeries> list = baseMapper.getCarSeriesListPage(ew, page);
        if (list != null && !list.isEmpty()) {
            for (CarSeries series : list) {
                EntityWrapper<CarModel> modelEw = new EntityWrapper<>();
                modelEw.eq("series_no", series.getNo());
                modelEw.eq("series_name", series.getName());
                modelEw.ne("status","50");
                List<CarModel> carModels = modelService.selectList(modelEw);
                series.setModels(carModels);
            }
        }
        page.setRecords(list);
        return page;
    }

}
